<template>
  <div>
    <el-form ref="form" :model="registerForm" status-icon :rules="rules">
      <el-form-item>
        <el-upload
            name="blogAvatars"
            class="avatar-uploader"
            :action="globalApi.uploadImg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
          <img v-if="registerForm.avatar" :src="registerForm.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item prop="userName">
        <el-input v-model="registerForm.userName" placeholder="请输入用户名" prefix-icon="el-icon-user-solid"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input show-password v-model="registerForm.password" placeholder="请输入密码" prefix-icon="el-icon-lock" />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input show-password v-model="registerForm.confirmPassword" placeholder="请再次输入密码" prefix-icon="el-icon-lock" />
      </el-form-item>
      <fx-verify-code v-if="false" ref="registerVerify"/>
      <el-button type="primary" plain style="width: 100%" @click="submit">立即注册</el-button>
    </el-form>
  </div>
</template>

<script>
import VerifyCode from "@/components/VerifyCode"
import globalApi from "@/config/globalApi"
import RegisterService from "@/service/users/RegisterService"
import pageUrl from '@/config/pageUrl'

export default {
  name: "RegisterPage",
  components:{
    'fx-verify-code': VerifyCode
  },
  created() {
    document.addEventListener('keydown', e => {
      if(e.key === 'Enter') {
        this.submit()
      }
    })
  },
  data(){

    const validateUserName = (rule, value, cb) => {
      if (!value) {
        return cb(new Error('请输入用户名！'))
      }
      if (value.length < 2 || value.length > 8) {
        return cb(new Error('用户名长度为 2~8 位字符！'))
      }
      if (value.includes(' ')) {
        return cb(new Error('用户名不能包含空格！'))
      }
      if (!/^[\u4E00-\u9FA5A-Za-z0-9]{2,8}$/.test(value)) {
        return cb(new Error('用户名只能包含中文、英文、数字！'))
      }
      cb()
    }

    const validatePassword = (rule, value, cb) => {
      if (!value) {
        return cb(new Error('请输入密码！'))
      }
      if (value.length < 6 || value.length > 16) {
        return cb(new Error('密码长度为 6~16 位字符！'))
      }
      if (value.includes(' ')) {
        return cb(new Error('密码不能包含空格！'))
      }
      if (/[\u4E00-\u9FA5]+/.test(value)) {
        return cb(new Error('密码不能包含中文！'))
      }
      if (!/^\S*(?=\S*\d)(?=\S*[a-zA-Z])\S*$/.test(value)) {
        return cb(new Error('密码必须包含数字和字母！'))
      }
      cb()
    }

    const validatePassword2 = (rule, value, cb) => {
      if (!value) {
        return cb(new Error('请确认密码！'))
      }
     if(value !== this.registerForm.password){
       return cb(new Error('两次输入的密码不一致！'))
     }
     cb()
    }

    return {
      // 注册信新表
      registerForm: {
        userName: '',
        password: '',
        confirmPassword: '',
        avatar: ''
      },
      rules:{
        userName: [{required: true, validator: validateUserName, trigger: 'blur'}],
        password: [{required: true, validator: validatePassword, trigger: 'blur'}],
        confirmPassword: [{required: true, validator: validatePassword2, trigger: 'blur'}],
      },
      globalApi
    }
  },
  methods: {
    // 头像获取
    handleAvatarSuccess(res) {
      this.registerForm.avatar = res.data.imgList[0]
    },
    // 提交注册
    submit(){
      // this.$refs.registerVerify.$refs.form.validate(valid => valid)
      // && this.$refs.registerVerify.isVerified
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 验证通过再发起注册请求
          let res = await RegisterService.register(this.registerForm)
          let {status,message} = res.data

          if(status === 500){
            this.$message.error('注册失败！ ' + message)
            return false
          }
          if(status === 200){
            this.$message.success(message)
            // 保存当前登录用户
            sessionStorage.setItem('currentUser', JSON.stringify({
              userName: this.registerForm.userName,
              password: this.registerForm.password + Math.floor(Math.random()*10)
            }))

            // 注册成功 把令牌存入到本地 sessionStorage 中 用于校验用户身份
            sessionStorage.setItem('authorization',res.headers['authorization'])
            setTimeout(() => {
              this.$message.success('即将跳转到主页...')
            },1000)
            // 登录成功跳转到主页面
            setTimeout(() => {
              location.replace(pageUrl.user)
            },1500)
          }
        } else {
          this.$message.error('请输入正确的格式！')
        }
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  left: 33%;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
